package com.java.oauth.controller;

import com.java.oauth.service.AuthService;
import com.java.oauth.service.UserLoginService;
import com.java.oauth.util.AuthToken;
import com.java.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录授权
 */
@RestController
@RequestMapping("/user")
public class UserLoginController {

	@Autowired
	private UserLoginService userLoginService;

	@Autowired
	private AuthService authService;

	//http://localhost:9001/user/login?username=admin&password=123456
	@RequestMapping("/login")
	public R login(String username, String password, HttpServletResponse response) {
		try {
//			AuthToken authToken = userLoginService.login(username, password);
			// userLoginService.login和authService.login是一样的.区别是authService.login对代码进行了抽取封装
			AuthToken authToken = authService.login(username, password);
			// 将token放到cookie中解析请求
			Cookie cookie = new Cookie("Authorization", authToken.getAccess_token());
			// 设置跨域
			cookie.setDomain("localhost");
			cookie.setPath("/");
			response.addCookie(cookie);
			return R.ok(authToken);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("登录失败,用户名或密码错误");
		}
	}


}
